
import threading
import os
from loguru import logger
from django.shortcuts import render
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.shortcuts import get_object_or_404
from django.conf import settings
import openai
import json
from .models import ChatSessionModel, ChatMessageModel
from .serializers import (
    ChatSessionSerializer, ChatSessionListSerializer, 
    ChatMessageSerializer, ChatMessageCreateSerializer
)
from apps.project.models import ProjectModel
from apps.middleware import CustomUserPermission, CustomUserAuthentication


# Create your views here.


_tag = "Chat"


class ChatSessionViewSet(viewsets.ModelViewSet):
    """聊天会话视图集"""
    queryset = ChatSessionModel.objects.all()
    serializer_class = ChatSessionSerializer
    permission_classes = [CustomUserPermission]
    authentication_classes = [CustomUserAuthentication]
    
    def get_queryset(self):
        """用户只能访问自己的聊天会话"""
        # 🔧 处理Swagger文档生成时的匿名用户问题
        if getattr(self, 'swagger_fake_view', False):
            return ChatSessionModel.objects.none()
        
        if not self.request.user.is_authenticated:
            return ChatSessionModel.objects.none()
            
        return ChatSessionModel.objects.filter(user=self.request.user)
    
    def get_serializer_class(self):
        """根据不同的action选择不同的序列化器"""
        if self.action == 'list':
            return ChatSessionListSerializer
        return ChatSessionSerializer
    
    def perform_create(self, serializer):
        """创建聊天会话时设置用户"""
        project_id = self.request.data.get('project_id')
        project = get_object_or_404(ProjectModel, id=project_id, creator=self.request.user)
        serializer.save(user=self.request.user, project=project)
    
    @action(detail=True, methods=['post'])
    def send_message(self, request, pk=None):
        """发送消息并获取AI回复"""
        session = self.get_object()
        serializer = ChatMessageCreateSerializer(
            data=request.data,
            context={'session': session}
        )
        serializer.is_valid(raise_exception=True)
        
        # 保存用户消息
        user_message = serializer.save()
        
        # 创建AI消息
        ai_message = ChatMessageModel.objects.create(
            session=session,
            role='assistant',
            content='',
            status='processing'
        )
        
        try:
            # 调用OpenAI API
            ai_response, markdown_content = self._generate_ai_response(session, user_message.content)
            
            # 更新AI消息
            ai_message.content = ai_response
            ai_message.generated_markdown = markdown_content
            ai_message.status = 'completed'
            ai_message.save()
            
            # 如果生成了markdown内容，更新项目
            project_updated = False
            if markdown_content:
                # 写入到index.md文件
                index_path = session.project.write_index_md(markdown_content)
                project_updated = True
                
                # 也更新background.md以反映最新状态
                session.project.update_background_md()
            
            # 返回两条消息
            messages = [
                ChatMessageSerializer(user_message).data,
                ChatMessageSerializer(ai_message).data
            ]
            
            return Response({
                'messages': messages,
                'project_updated': project_updated,
                'index_md_path': index_path if project_updated else None
            })
            
        except Exception as e:
            ai_message.content = f'抱歉，AI服务暂时不可用: {str(e)}'
            ai_message.status = 'error'
            ai_message.save()
            
            return Response({
                'messages': [
                    ChatMessageSerializer(user_message).data,
                    ChatMessageSerializer(ai_message).data
                ],
                'error': str(e)
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def _generate_ai_response(self, session, user_content):
        """生成AI回复"""
        # 配置OpenAI客户端
        client = openai.OpenAI(
            api_key=settings.OPENAI_API_KEY,
            base_url=settings.OPENAI_API_BASE
        )
        
        # 获取项目背景信息
        project_background = session.project.get_background_content()
        
        # 构建对话历史
        messages = []
        
        # 系统提示，包含项目背景
        system_prompt = f"""你是一个专业的markdown文档助手。你的任务是帮助用户生成、编辑和优化markdown文档。

## 项目背景信息
{project_background}

## 当前项目状态
- 当前文档内容：{session.project.current_content or '暂无内容'}

## 指导原则
1. 请根据项目背景信息和已有文件内容来回答用户问题
2. 如果用户要求生成新内容，请基于项目背景和现有资源进行创作
3. 如果用户要求修改现有内容，请基于当前内容进行优化
4. 生成的内容应该与项目的整体风格和主题保持一致
5. 可以引用项目中的文件和资源
6. 请用中文回复
7. 生成的内容应该是完整的markdown文档

注意：请充分利用项目背景信息中的文件内容和目录结构来提供更准确、更专业的回答。
"""
        
        messages.append({"role": "system", "content": system_prompt})
        
        # 添加对话历史（最近10条）
        recent_messages = session.messages.order_by('-created_at')[:10]
        for msg in reversed(recent_messages):
            if msg.role in ['user', 'assistant']:
                messages.append({
                    "role": msg.role,
                    "content": msg.content
                })
        
        # 添加当前用户消息
        messages.append({"role": "user", "content": user_content})
        
        # 调用OpenAI API
        response = client.chat.completions.create(
            model=settings.OPENAI_MODEL,
            messages=messages,
            max_tokens=4000,
            temperature=0.7
        )
        
        ai_response = response.choices[0].message.content
        
        # 检查回复是否包含markdown内容
        markdown_content = None
        if any(keyword in user_content.lower() for keyword in ['生成', '创建', '写', '修改', '更新', 'markdown', '文档']):
            # 如果用户要求生成或修改内容，将AI回复作为markdown内容
            markdown_content = ai_response
        
        return ai_response, markdown_content


class ChatMessageViewSet(viewsets.ReadOnlyModelViewSet):
    """聊天消息视图集（只读）"""
    queryset = ChatMessageModel.objects.all()
    serializer_class = ChatMessageSerializer
    permission_classes = [CustomUserPermission]
    authentication_classes = [CustomUserAuthentication]
    
    def get_queryset(self):
        """用户只能访问自己会话的消息"""
        # 🔧 处理Swagger文档生成时的匿名用户问题
        if getattr(self, 'swagger_fake_view', False):
            return ChatMessageModel.objects.none()
        
        if not self.request.user.is_authenticated:
            return ChatMessageModel.objects.none()
            
        return ChatMessageModel.objects.filter(session__user=self.request.user)

